
Ext.onReady(function(){
    var current_order_id; //当前选择的order的id
    var current_ticket_id; //当前选择的ticket的id
    var current_order_status; //当前order的状态
    var current_ticket_status; //当前ticket的状态
    var ordersrow;
    var ticketsrow;
    var group_flag;
    
    var comingPhone = new Ext.form.TextField({
        fieldLabel: '来电号码',
        //allowBlank: false,
        name: 'coming_phone',
        anchor: '90%',
        readOnly: true,
        value: phone_number
    });
    
    var customerNameDS = new Ext.data.Store({
        proxy: new Ext.data.HttpProxy({
            url: '/customers/getCustomersLikeName'
        }),
        reader: new Ext.data.JsonReader({
            totalProperty: 'totalProperty',
            root: 'root'
        }, [{
            name: 'id'
        }, {
            name: 'name'
        }, {
            name: 'sex'
        }, {
            name: 'phone'
        }])
    });
    
    var customer_name_resultTpl = new Ext.XTemplate('<tpl for="."><div class="search-item">', '{name} {phone}', '</div></tpl>');
    var customerName = new Ext.form.ComboBox({
        store: customerNameDS,
        fieldLabel: '客户名称',
        name: 'customer_name',
        typeAhead: false,
        loadingText: '搜索中...',
        anchor: '90%',
        //pageSize: 10,
        //hideTrigger: true,
        tpl: customer_name_resultTpl,
        minChars: 1,
        itemSelector: 'div.search-item',
        value: customer_name,
        onSelect: function(record){
            if (this.isExpanded()) {
                this.collapse();
            }
            window.document.location.href = "/index/phoneshow?phone_number=" + record.data.phone;
        }
    });
    
    var customerPhone = new Ext.form.TextField({
        fieldLabel: '客户电话',
        //allowBlank: false,
        name: 'phone',
        anchor: '90%',
        value: customer_phone,
        listeners: {
            specialkey: function(field, e){
                if (e.getKey() == Ext.EventObject.ENTER) {
                    window.document.location.href = '/index/phoneshow?phone_number=' + customerPhone.getValue();
                }
            }
        }
    });
    
    var customerSex = new Ext.form.TextField({
        fieldLabel: '性别',
        //allowBlank: false,
        name: 'sex',
        anchor: '90%',
        readOnly: true,
        value: customer_sex
    });
    
    var customerNo = new Ext.form.TextField({
        fieldLabel: '会员卡号',
        //allowBlank: false,
        name: 'customer_no',
        anchor: '90%',
        value: customer_no,
        listeners: {
            specialkey: function(field, e){
                if (e.getKey() == Ext.EventObject.ENTER) {
                    Ext.Ajax.request({
                        url: '/customers/checkCustomerNo?customer_no=' + customerNo.getValue(),
                        method: 'GET',
                        success: function(result, request){
                            if (result.responseText.indexOf("失败") < 0) {
                                window.document.location.href = "/index/phoneshow?phone_number=" + result.responseText;
                            //var url = '/customers/customerInfoByID?customer_no=' + customerNo.getValue();
                            //Ext.getCmp('phoneshow_tab0').getUpdater().update(url);
                            }
                            else {
                                Ext.MessageBox.alert('提示', "未发现此用户");
                            }
                        },
                        failure: function(result, request){
                            Ext.MessageBox.alert('提示', '根据会员卡号得到用户失败!');
                        }
                    });
                    
                }
            }
        }
    });
    
    var customerAge = new Ext.form.TextField({
        fieldLabel: '年龄',
        //allowBlank: false,
        name: 'age',
        readOnly: true,
        anchor: '90%',
        value: customer_age
    });
    
    var customerType = new Ext.form.TextField({
        fieldLabel: '客户类型',
        //allowBlank: false,
        name: 'customer_type',
        readOnly: true,
        anchor: '90%',
        value: customer_type
    });
    
    var linkMan = new Ext.form.TextField({
        fieldLabel: '联系人',
        //allowBlank: false,
        name: 'link_man',
        readOnly: true,
        anchor: '90%',
        value: customer_linkman
    });
    
    var customerAddress = new Ext.form.TextField({
        fieldLabel: '地址',
        //allowBlank: false,
        name: 'address',
        readOnly: true,
        anchor: '90%',
        value: customer_address
    });
    
    var customerRemark = new Ext.form.TextField({
        fieldLabel: '备注',
        //allowBlank: false,
        name: 'remark',
        anchor: '90%',
        value: customer_remark
    });
    
    var saveRemarkButton = new Ext.Button({
        text: '保存备注',
        handler: saveRemark
    })
    
    function saveRemark(){
        if (customerRemark.getValue() != "") {
            Ext.Ajax.request({
                url: '/customers/saveRemark?customer_id=' + customerid + '&remark=' + encodeURIComponent(customerRemark.getValue()),
                method: 'GET',
                success: function(result, request){
                    Ext.MessageBox.alert('提示', '保存用户备注成功!');
                },
                failure: function(result, request){
                    Ext.MessageBox.alert('提示', '保存用户备注失败!');
                }
            })
        }
    }
    
    var addNewCustomerButton = new Ext.Button({
        text: '添加客户',
        handler: addCustomer
    })
    
    function addCustomer(){
        CreateCustomer(null, comingPhone.getValue());
    }
    
    var userInfoFormPanel = new Ext.form.FormPanel({
        //baseCls: 'x-plain',
        labelWidth: 65,
        labelAlign: 'right',
        frame: true,
        url: '/customers/addCustomer',
        //defaultType: 'textfield',
        items: [{
            layout: 'column',
            border: false,
            items: [{
                columnWidth: .25,
                layout: 'form',
                border: false,
                items: [comingPhone]
            }, {
                columnWidth: .25,
                layout: 'form',
                border: false,
                items: [customerName]
            }, {
                columnWidth: .25,
                layout: 'form',
                border: false,
                items: [customerSex]
            }, {
                columnWidth: .25,
                layout: 'form',
                border: false,
                items: [customerAge]
            }]
        }, {
            layout: 'column',
            border: false,
            items: [{
                columnWidth: .25,
                layout: 'form',
                border: false,
                items: [customerPhone]
            }, {
                columnWidth: .25,
                layout: 'form',
                border: false,
                items: [customerNo]
            }, {
                columnWidth: .25,
                layout: 'form',
                border: false,
                items: [customerType]
            }, {
                columnWidth: .25,
                layout: 'form',
                border: false,
                items: [linkMan]
            }]
        }, {
            layout: 'column',
            border: false,
            items: [{
                columnWidth: .25,
                layout: 'form',
                border: false,
                items: [customerAddress]
            }, {
                columnWidth: .525,
                layout: 'form',
                border: false,
                items: [customerRemark]
            }, {
                columnWidth: .1,
                layout: 'form',
                border: false,
                items: [saveRemarkButton]
            }, {
                columnWidth: .125,
                layout: 'form',
                border: false,
                items: [addNewCustomerButton]
            }]
        }]//, customerLevel]
    });
    userInfoFormPanel.render('user_info_form');
    
    //---------------------GRID-----------------------------------
    var ordercm = new Ext.grid.ColumnModel([new Ext.grid.RowNumberer(), {
        header: '编号',
        dataIndex: 'id',
        hidden: true
    }, {
        header: '订单编号',
        dataIndex: 'order_no',
        sortable: true,
        width: 115
    }, {
        header: 'PNR',
        dataIndex: 'pnr',
        sortable: true,
        width: 55
    }, {
        header: '客户名称',
        dataIndex: 'customer',
        sortable: true,
        width: 70
    }, {
        header: '订单状态',
        dataIndex: 'status',
        sortable: true,
        width: 60
    }, {
        header: '订单类型',
        dataIndex: 'status',
        width: 60,
        renderer: typeRender
    }, {
        header: '总金额',
        dataIndex: 'price_sum',
        sortable: true,
        width: 50
    }, {
        header: '乘机日期',
        dataIndex: 'fly_date',
        sortable: true,
        width: 70
    }, {
        header: '起飞(T)',
        dataIndex: 'fly_time',
        sortable: true,
        width: 50
    }, {
        header: '送票地址',
        dataIndex: 'send_address',
        sortable: true,
        width: 130
    }, {
        header: '联系人',
        dataIndex: 'link_man',
        sortable: true,
        width: 50
    }, {
        header: '联系电话',
        dataIndex: 'link_tel',
        sortable: true,
        width: 90
    }, {
        header: '接机(T)',
        dataIndex: 'jj_time',
        sortable: true,
        width: 50
    }, {
        header: '接机地址',
        dataIndex: 'jj_address',
        sortable: true,
        width: 100
    }, {
        header: '预定员',
        dataIndex: 'creator',
        sortable: true,
        width: 50
    }, {
        header: '预定(T)',
        dataIndex: 'created_at',
        sortable: true,
        width: 110,
        renderer: Ext.util.Format.dateRenderer('Y-m-d H:i')
    }, {
        header: '客户要求',
        dataIndex: 'order_request',
        sortable: true,
        width: 120
    }]);
    var orderds = new Ext.data.Store({
        proxy: new Ext.data.HttpProxy({
            url: '/orders/getOrdersByCustomerID?id=' + customerid
        }),
        reader: orderReader
    });
    
    function typeRender(value, cellmeta, record, rowIndex, columnIndex, store){
        var order_type = "";
        if (record.get("web")!=""){
            order_type += "网络";
        }
        if (record.get("international")!=""){
            order_type += "国际";
        }
        if (record.get("group")!=""){
            order_type += "团体";
        }
        return order_type;
    }
    var ordergridpanel = new Ext.grid.GridPanel({
        el: 'ordersgrid',
        ds: orderds,
        cm: ordercm,
        loadMask: true,
        autoWidth: true,
        collapsible: true,
        animCollapse: false,
        //frame: true,
        height: 250,
        title: '订单列表'
    });
    ordergridpanel.render();
    orderds.load();

    //双击订单查看票详细
    ordergridpanel.on('rowdblclick', function(ordergridpanel, rowIndex, e){
        var current_order_selected = orderds.data.items[rowIndex].id;
        ordersrow = orderds.getById(current_order_selected);//ds为绑定到grid的数据源
        current_order_id = ordersrow.get("id");
        current_order_status = ordersrow.get("status");
        group_flag = ordersrow.get("group");
        ticketds.baseParams.id = current_order_id;
        ticketds.reload();
    });
    //订单右键菜单
    ordergridpanel.on('rowcontextmenu', function(customergridpanel, rowIndex, e){
        var current_order_selected = orderds.data.items[rowIndex].id;
        ordersrow = orderds.getById(current_order_selected);//ds为绑定到grid的数据源
        current_order_id = ordersrow.get("id");
        current_order_status = ordersrow.get("status");
        group_flag = ordersrow.get("group");
        if (group_flag.indexOf("团体")>=0 || group_flag.indexOf("团队")>=0){
            if (group_flag.indexOf("满员")>=0){
                addGroupPassItem.disable();
                modPassNumItem.disable();
            }
            e.preventDefault();
            rightClick_group.showAt(e.getXY());
        }else{
            e.preventDefault();
            rightClick.showAt(e.getXY());
        }
    });
    //############ 订单-右键菜单 ##########
    function rightMenu1Fn(){
        ModOrder(orderds, current_order_id, ticketds);
    }
    function rightMenu2Fn(){
        var current_order_no = ordersrow.get("order_no");
        cancelOrder(current_order_status, current_order_id, current_order_no, orderds, ticketds);
    }
    function rightMenu3Fn(){
        if (customerid && customerid != "") {
            showCustomerInfo(customerid);
        }
        else {
            var c_id_par = ordersrow.get("customer_id");
            showCustomerInfo(c_id_par);
        }
    }
    function rightMenu4Fn(){
        showPnrInfo(current_order_id);
    }
    function rightMenu5Fn(){
        changeCustomer(orderds, current_order_id, ticketds);
    }
    function rightMenu6Fn(){
        var c_id_par = ordersrow.get("customer_id");
        window.location.href = "/index/phoneshow?id=" + c_id_par + "&oid=" + current_order_id + "&option=mod";
    }
    function rightMenu7Fn(){
        joinActivity(current_order_id, orderds, ticketds);
    }
    function rightMenu8Fn(){
        var c_id_par = ordersrow.get("customer_id");
        window.location.href = "/index/phoneshow?id=" + c_id_par + "&oid=" + current_order_id + "&option=add";
    }
    function rightMenu9Fn(){
        saPnrFunction(current_order_id,orderds,ticketds);
    }
    function myOrderSendSMS(){
        var current_link_tel = ordersrow.get("link_tel");
        sendSMS(current_link_tel);
    }
    function addGroupPass(){
        var url = "/orders/addGroupPassengers?orderid="+current_order_id;
        var tabs = Ext.getCmp('tabs');
        var addGroupPassTab = Ext.getCmp('add_group_pass_tab');
        if (addGroupPassTab) {
            //addGroupPassTab.getUpdater().update(url);
            tabs.activate(addGroupPassTab);
        }
        else {
            tabs.add({
                id: 'add_group_pass_tab',
                title: "追加团体乘客",
                //disabled: true,
                autoLoad: {
                    url: url,
                    scripts: true
                },
                closable: true
            }).show();
        }
    }
    function modPassNum(){
        var seat_default = parseInt(ordersrow.get("seat"));
        var seatArray = [];
        for(var i=10;i<=seat_default;i++){
            seatArray.push([i]);
        }
        var groupPassNum = new Ext.form.ComboBox({ //combobox
            name: 'seat_number',
            fieldLabel: '人数',
            resiable: true,
            typeAhead: true,
            handleHeight: 100, //
            displayField: 'value',
            valueField: 'value',
            selectOnFocus: true,
            mode: 'local',
            width: 60,
            triggerAction: 'all',//这个属性非常重要,可以在选择一个值以后,依然还显示其它的值.
            readOnly: true,
            value: seat_default,
            store: new Ext.data.Store({
                reader: new Ext.data.ArrayReader({}, ['value']),
                data: seatArray
            }) //数据储存到这个comboBox
        });
 
        var formPanel = new Ext.form.FormPanel({
            //baseCls: 'x-plain',
            labelWidth: 50,
            labelAlign: 'right',
            frame: true,
            url: "/orders/modGroupPassNum?id=" + current_order_id,
            items: [groupPassNum]
        });
    
        var fixWindow = new Ext.Window({
            title: '修改团队人数',
            width: 200,
            height: 130,
            layout: 'fit',
            plain: true,
            bodyStyle: 'padding:5px;',
            buttonAlign: 'center',
            items: formPanel,
            buttons: [{
                text: '保存',
                handler: function(){
                    // check form value
                    if (formPanel.form.isValid()) {
                        formPanel.form.submit({
                            waitMsg: 'In processing',
                            success: function(form, action){
                                var info = "操作失败，具体失败原因请查询系统日志";
                                if (action.result && action.result.info && action.result.info != "") {
                                    info = action.result.info;
                                }
                                if (info.indexOf("成功") >= 0) {
                                    Ext.MessageBox.alert('操作成功', info);
                                    fixWindow.hide();
                                }else{
                                    Ext.MessageBox.alert('操作失败', info);
                                }
                            },
                            failure: function(form, action){
                                Ext.MessageBox.alert('操作信息', '操作失败');
                            }
                        });
                    }
                    else {
                        Ext.MessageBox.alert('错误消息', '请将必填项信息录入后再提交.');
                    }
                }
            }, {
                text: '取消',
                handler: function(){
                    fixWindow.hide();
                }
            }]
        });
        fixWindow.show();
    }
    var addGroupPassItem = new Ext.menu.Item({
        text: '【录入团队乘客】',
        //iconCls: 'album',
        handler: addGroupPass
    });
    var modPassNumItem = new Ext.menu.Item({
        text: '【修改团队人数】',
        //iconCls: 'album',
        handler: modPassNum
    });
    var rightClick = new Ext.menu.Menu({
        items: [{
            handler: rightMenu4Fn,
            text: '【提取PNR】'
        }, {
            handler: rightMenu3Fn,
            text: '【查看客户】'
        }, "-", {
            handler: rightMenu1Fn,
            text: '【修改订单】'
        }, {
            handler: rightMenu2Fn,
            text: '【取消订单】'
        }, {
            handler: rightMenu5Fn,
            text: '【订单转换】'
        }, {
            handler: rightMenu6Fn,
            text: '【修改航段】'
        }, {
            handler: rightMenu8Fn,
            text: '【追加航段】'
        }, {
            handler: rightMenu9Fn,
            text: '【分离PNR】'
        }, "-", {
            handler: rightMenu7Fn,
            text: '【参加活动】'
        }, {
            text: '【发送短信】',
            handler: myOrderSendSMS
        }]
    });
    var rightClick_group = new Ext.menu.Menu({
        items: [{
            handler: rightMenu4Fn,
            text: '【提取PNR】'
        }, {
            handler: rightMenu3Fn,
            text: '【查看客户】'
        }, "-", {
            handler: rightMenu1Fn,
            text: '【修改订单】'
        }, {
            handler: rightMenu2Fn,
            text: '【取消订单】'
        }, {
            handler: rightMenu5Fn,
            text: '【订单转换】'
        }, {
            handler: rightMenu6Fn,
            text: '【修改航段】'
        }, {
            handler: rightMenu8Fn,
            text: '【追加航段】'
        }, {
            handler: rightMenu9Fn,
            text: '【分离PNR】'
        }, "-", addGroupPassItem, modPassNumItem, "-", {
            handler: rightMenu7Fn,
            text: '【参加活动】'
        }, {
            text: '【发送短信】',
            handler: myOrderSendSMS
        }]
    });
    
    //---------ready grid for plane ticket----------------------------------
    var ticketcm = new Ext.grid.ColumnModel([new Ext.grid.RowNumberer(), {
        header: '编号',
        dataIndex: 'id',
        hidden: true
    }, {
        header: 'PNR',
        dataIndex: 'pnr',
        width: 60
    }, {
        header: '旅客姓名',
        dataIndex: 'passenger_name',
        width: 60
    }, {
        header: '证件号码',
        dataIndex: 'card',
        width: 140
    }, {
        header: '票号',
        dataIndex: 'ticket_no',
        width: 110
    }, {
        header: '类型',
        dataIndex: 'ticket_type',
        width: 50
    }, {
        header: '状态',
        dataIndex: 'status',
        width: 70
    }, {
        header: '出票状态',
        dataIndex: 'status_type',
        width: 70
    }, {
        header: '航班号',
        dataIndex: 'air_no',
        width: 70
    }, {
        header: '航程',
        dataIndex: 'fromto',
        width: 70
    }, {
        header: '乘机日期',
        dataIndex: 'fly_date',
        width: 100
    }, {
        header: '起飞时间',
        dataIndex: 'fly_time',
        width: 70
    }, {
        header: '舱位',
        dataIndex: 'position',
        width: 50
    }, {
        header: '机票价格',
        dataIndex: 'price',
        width: 70
    }, {
        header: '机场费税',
        dataIndex: 'airdrome_tax',
        width: 50
    }, {
        header: '附加费',
        dataIndex: 'fuel_tax',
        width: 50
    }, {
        header: 'F',
        dataIndex: 'price_F',
        width: 50
    }, {
        header: '积分',
        dataIndex: 'point',
        width: 50
    }, {
        header: '保险份数',
        dataIndex: 'insurance_number',
        width: 50
    }, {
        header: '保险F',
        dataIndex: 'insurance_F',
        width: 50
    }, {
        header: '其他',
        dataIndex: 'other',
        width: 50
    }, {
        header: '合计',
        dataIndex: 'total_price',
        width: 70
    }]);
    ticketcm.defaultSortable = true;
    var ticketProxy = new Ext.data.HttpProxy({
        url: '/orders/getTicketsByOrderID?showCancelTicket=no'
    });
    var ticketds = new Ext.data.Store({
        proxy: ticketProxy,
        reader: ticketReader
    });
    var ticketgridpanel = new Ext.grid.GridPanel({
        el: 'ticketsgrid',
        ds: ticketds,
        cm: ticketcm,
        //sm: sm,
        loadMask: true,
        autoWidth: true,
        collapsible: true,
        animCollapse: false,
        //frame: true,
        height: 180,
        title: '机票列表'
    });
    ticketgridpanel.render();
    ticketds.load();
    
    //############ 票-右键菜单 ##########
    function ticketRightMenu1(){
        ModTicket(ticketds, current_ticket_id, orderds);
    }
    function ticketRightMenu2(){
        if (group_flag.indexOf("团体")>=0 && group_flag.indexOf("满员")<0){
            Ext.MessageBox.alert('提示', '团体票必须录入乘客信息后才能取消乘客');
        }else{
            var current_passenger_name = ticketsrow.get("passenger_name");
            cancelTicket(current_ticket_status, current_ticket_id, current_passenger_name, ticketds);
        }
    }
    function ticketRightMenu3(){
        var ticket_type = ticketsrow.get("ticket_type");
        if (ticket_type && ticket_type == "婴儿") {
            Ext.MessageBox.alert('操作提示', '这张票是婴儿票');
        }
        else if (ticket_type && ticket_type == "儿童") {
            Ext.MessageBox.alert('操作提示', '这张票是儿童票');
        }
        else {
            addChild(ticketds, current_ticket_id);
        }
    }
    //菜单
    var ticketRightClick = new Ext.menu.Menu({
        items: [{
            handler: ticketRightMenu1,
            text: '【编辑修改】'
        }, {
            handler: ticketRightMenu2,
            text: '【取消乘客】'
        }, "-", {
            handler: ticketRightMenu3,
            text: '【追加婴儿】'
        }]
    });
    ticketgridpanel.on('rowcontextmenu', function(ticketgridpanel, rowIndex, e){
        var current_ticket_selected = ticketds.data.items[rowIndex].id;
        ticketsrow = ticketds.getById(current_ticket_selected);//ds为绑定到grid的数据源
        current_ticket_id = ticketsrow.get("id");
        current_ticket_status = ticketsrow.get("status");
        e.preventDefault();
        ticketRightClick.showAt(e.getXY());
    });
})
